﻿using CL.Business.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CL.Business.Entity;
using CL.Tools.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using CL.Game.BLL;
using CL.Game.Entity;
using CL.Json.Entity;
using System.Web.Http.Results;
using CL.Json.Entity.WebAPI;


namespace CL.UnionWeb
{
    /// <summary>
    /// Register1 的摘要说明
    /// </summary>
    public class Register1 : IHttpHandler
    {
        protected static UsersBLL bll = new UsersBLL();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";//这才是输出Json
            var acti = context.Request["action"];
            if (null == acti)
            {
                context.Response.Write("error");
                context.Response.End();
            }

            string action = acti.Trim();
            switch (action)
            {
                //判断用户名是否存在
                case "CheckAccount":
                    context.Response.Write(CheckAccount(context));
                    break;
                //验证身份证号码的正确性
                case "CheckIDCard":
                    string card = context.Request.QueryString["card"].Trim();
                    context.Response.Write(CheckIDCard(card));
                    break;
                //验证用户是否注册成会员用户
                case "IsMobileRegistered":
                    context.Response.Write(IsMobileRegistered(context));
                    break;
                //验证手机号码是否已注册
                case "ExistPhoneNumber":
                    context.Response.Write(CheckUserMobileExist(context));
                    break;
                //获取验证码
                case "SendCheckCode":
                    context.Response.Write(SendCheckCode(context));
                    break;
                //判断身份证号码是否被注册过
                case "QueryEntityByIdCard":
                    string idNumber = context.Request.QueryString["idCard"].Trim();
                    context.Response.Write(QueryEntityByIdCard(idNumber));
                    break;
                //新用户注册成为会员
                case "UserRegister":
                    string userphone = context.Request["userphone"];
                    string userpwd = context.Request["userpwd"];
                    string checkCode = context.Request["checkCode"];
                    string accountid = context.Request["accountid"];
                    LoginResult result = new UsersBLL().MobileRegister("", 0, userphone, userpwd, checkCode);
                    if (result.Code == 0)
                    {
                        if (result.Data.UserCode > 0)
                        {
                            //会员注册
                            new AgencyUserBLL().InsertEntity(new AgencyUserEntity()
                            {
                                AccountID = int.Parse(accountid),
                                UserID = int.Parse(result.Data.UserCode.ToString()),
                                StartTime = DateTime.Now,
                                EndTime = DateTime.Now.AddYears(1)
                            });
                            context.Response.Write(result.Data.UserCode);
                        }
                    }
                    break;
                case "QueryEntityByBankID":
                    string bankcard = context.Request["bankcard"];
                    context.Response.Write(QueryEntityByBankID(bankcard));
                    break;
                case "BindVipInfo":
                    context.Response.Write(BindVipInfo(context));
                    break;
                case "GetPhone":
                    GetPhoneFromAccountID(context);
                    break;
            }
            context.Response.End();
        }

        public bool CheckIDCard(string idNumber)
        {
            if (idNumber.Length == 18)
            {
                //bool check = CheckIDCard18(idNumber);
                //return check;
                return true;
            }
            else
            {
                return false;
            }
        }

        public void GetPhoneFromAccountID(HttpContext context)
        {
            string account = context.Request["account"].ToString();
            var entity = new AccountBLL().QueryEntity(account);
            if (null == entity)
            {
                context.Response.Write("该用户不存在");
            }
            else
            {
                context.Response.Write("ok_" + entity.UserMobile.Substring(entity.UserMobile.Length - 4, 4));
            }
        }

        public bool CheckUserMobileExist(HttpContext context)
        {
            string phone = context.Request["phone"].ToString();
            var entity = new AccountBLL().QueryEntityByMoblie(phone);
            return null != entity;
        }

        public bool QueryEntityByBankID(string bankcard)
        {
            AccountEntity entity = new AccountBLL().QueryEntityByBankID(bankcard);
            if (entity != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public string BindVipInfo(HttpContext context)
        {
            //绑定银行卡
            string userIDcard = context.Request["userIDcard"];
            string bankname = context.Request["bankname"];
            string bankcard = context.Request["bankcard"];
            string userCode = context.Request["userCode"];
            string mobile = new UsersBLL().QueryEntityByUserCode(long.Parse(userCode)).UserMobile;
            string VerifyCode = context.Request["checkCode"];
            UsersExtendEntity userinfo = new UsersExtendBLL().QueryEntityByUserCode(long.Parse(userCode));
            userinfo.IDNumber = userIDcard;
            new UsersExtendBLL().ModifyEntity(userinfo);
            var result = new UsersBanksBLL().BindBankCard(long.Parse(userCode), bankname, bankcard, string.Empty, mobile, VerifyCode);
            return result.Msg;
        }


        public bool QueryEntityByIdCard(string idNumber)
        {
            AccountEntity entity = new AccountBLL().QueryEntityByIdCard(idNumber);
            if (entity != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>  
        /// 18位身份证号码验证  
        /// </summary>  
        /// <param name="idNumber"></param>  
        /// <returns></returns>  
        public bool CheckIDCard18(string idNumber)
        {
            long n = 0;
            if (long.TryParse(idNumber.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证    
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(idNumber.Remove(2)) == -1)
            {
                return false;//省份验证    
            }
            string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证    
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = idNumber.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            Console.WriteLine("Y的理论值: " + y);
            if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower())
            {
                return false;//校验码验证    
            }
            return true;//符合GB11643-1999标准    
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public bool CheckAccount(HttpContext context)
        {
            string account = context.Request.Params["account"].ToString();
            AccountEntity entity = new AccountBLL().QueryEntity(account);
            if (entity != null)
            {
                return true;
            }
            return false;
        }
        public bool IsMobileRegistered(HttpContext context)
        {
            string phone = context.Request.QueryString["phone"].Trim();
            UsersEntity entity = new UsersBLL().QueryEntityByUserMobile(phone);
            if (entity != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        public string SendCheckCode(HttpContext context)
        {
            string phone = context.Request.QueryString["phone"].Trim();
            string userCode = context.Request["userCode"];
            if (!string.IsNullOrEmpty(userCode))
            {
                phone = new UsersBLL().QueryEntityByUserCode(long.Parse(userCode)).UserMobile;
            }
            JsonResult result = new UsersBLL().SendVerifyCode("", "", phone, 0);
            return result.Msg;
        }
    }
}